import {AfterViewInit, Component, OnInit, ViewChild} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {DatePipe} from '@angular/common';
import {CooperationService} from '../../../cooperation/cooperation.service';
import {NzMessageService} from 'ng-zorro-antd/message';
import {NzModalService} from 'ng-zorro-antd/modal';
import {Router} from '@angular/router';
import {UsedStorePService} from '../../used-store-p.service';
import {DeviceStatus, ChannelOccupy} from '../../used-store-manage.pipe';
import {UsedStoreZservice} from '../../used-store-zservice';
import {getLodop} from '../../../../../assets/LodopFuncs';
import {NzUploadFile} from 'ng-zorro-antd/upload';
import {PermissionService} from '../../../../service/permission.service';

interface TrackModal {
  visible: boolean; // 模态框显隐
  loading: boolean; // 按钮是否加载中
  id: string; // id
  url: string; // 文件
  remark: string; // 跟进内容
  file: any; // 跟进文件
}

@Component({
  selector: 'app-device-list',
  templateUrl: './device-list.component.html',
  styleUrls: ['./device-list.component.scss'],
  providers: [DatePipe]
})
export class DeviceListComponent implements OnInit {

  constructor(
    private datePipe: DatePipe,
    private nzMessageService: NzMessageService,
    private nzModalService: NzModalService,
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private usedStorePService: UsedStorePService,
    private usedStoreZservice: UsedStoreZservice,
    public permissionService: PermissionService
  ) {
    activatedRoute.queryParams.subscribe((res: any) => {
      this.query.code = res.code || '';
    });
  }
  DEVICESTATUS = DeviceStatus;
  CHANNELOCCUPY = ChannelOccupy;
  @ViewChild('reportModalRef') reportModalRef: any;
  LODOP: any;
  dbclick: any;
  deviceInfo = {
    type: '',
    color: '',
    memory: '',
    version: '',
    network: '',
    serial: '',
    serialNumber: '',
    imei: '',
    chargeCount: '',
    batteryHealth: '',
  };
  query = {
    code: null, // 编码
    status: [], // 状态
    occupyStatus: [], // 渠道占用
    libraryId: [], // 库位
    colourId: [], // 成色
    typeId: [], // 设备品牌
    modelId: [], // 设备型号
    sourceList: [], // 来源 0回收 1重新入库
    first: null, // 首次入库时间
    machineDates: null, // 验机时间
    finished: null, // 成交入库时间
    up: null, // 上架时间
    out: null, // 出库时间
    page: 1, // 当前页
    pageSize: 20, // 分页大小
  };
  listOfData = {
    page: 1,
    total: 100,
    pageSize: 20,
    records: []
  };
  modal = {
    modalVisible: false,
    operationType: '',
    loading: false,
  };
  formData = {
    id: '',
    date: '',
    productId: '',
    registerCount: 0,
    rechargeAmount: 0,
  };
  appOptions: any[] = [];
  // 修改库位模态框
  changeDLModal = {
    visible: false,
    libraryId: '', // 库位id
  };
  // 库位待选项
  locationOptions: any[] = [];
  // 品牌待选项
  brandOptions: any[] = [];
  // 机型待选项
  typeOptions: any[] = [];
  // 成色待选项
  colourOptions: any[] = [];
  //  跟进
  trackModal: TrackModal = {
    visible: false,
    loading: false,
    id: '',
    url: '',
    remark: '',
    file: [],
  };
  trackHistoryList: any[] = [];
  // 显示所有设备 显示在库设备
  showAllDevice = 'all';
  // 选择
  checked = false;
  indeterminate = false;
  setOfCheckedId = new Set<number>();

  // 来源options
  sourceOptions = [
    {value: 0, label: '回收'},
    {value: 1, label: '重新入库'}
  ];
  beforeUpload = (file: NzUploadFile): boolean => {
    const acceptFileType = [
      'bmp', 'jpg', 'png', 'tif', 'gif', 'pcx', 'tga', 'exif',
      'fpx', 'svg', 'psd', 'cdr', 'pcd', 'dxf', 'ufo', 'eps',
      'ai', 'raw', 'WMF', 'webp', 'avif', 'apng', 'pdf', 'txt',
      'xls', 'xlsx', 'doc', 'docx', 'ppt', 'pptx',
    ];
    const fileName: any = file.name.split('.').pop();
    if (!acceptFileType.includes(fileName)) {
      this.nzMessageService.warning('暂不支持该文件类型');
      return false;
    }
    console.log(file);
    this.trackModal.file = [file];
    return false;
  };

  async ngOnInit() {
    this.queryList();
    await this.usedStorePService.dictData('machine_condition').then((res: any) => {
      if (res.code === 0) {
        this.colourOptions = res.data.list.records;
      }
    });
    await this.usedStoreZservice.recycleLibraryList({page: 1, pageSize: 9999}).then((res: any) => {
      if (res.code === 0) {
        this.locationOptions = res.data.records;
      }
    });
    this.usedStorePService.getBrandList().then((res: any) => {
      if (res.code === 0) {
        this.brandOptions = res.data.records;
      }
    });
    setTimeout(() => {
      this.LODOP = getLodop(document.getElementById('LODOP_OB'), document.getElementById('LODOP_EM'));
      if (!this.LODOP) {
        this.nzMessageService.warning('未安装打印插件');
        return;
      }
      let count = 0;
      for (let i = 0; i < this.LODOP.GET_PRINTER_COUNT(); i++) {
        if (this.LODOP.GET_PRINTER_NAME(i).includes('BTP')) {
          count += 1;
          this.LODOP.SET_PRINTER_INDEXA(i);
        }
      }
      if (count === 0) {
        this.nzMessageService.warning('未找到包含BTP的打印机，请手动设置');
      } else if (count === 1) {
        this.nzMessageService.success('打印机初始化成功');
      } else if (count > 1) {
        this.nzMessageService.success('找到两台包含BTP的打印机，将选择最后一台作为默认设备');
      }
    }, 1000);
  }

  getTypeList() {
    this.query.modelId = [];
    if (!this.query.typeId.join(',')) {
      this.typeOptions = [];
      return;
    }
    this.usedStorePService.getTypeList(this.query.typeId.join(',')).then((res: any) => {
      if (res.code === 0) {
        this.typeOptions = res.data.records;
      }
    });
  }

  queryBtn() {
    this.query.page = 1;
    this.queryList();
  }

  resetQuery() {
    this.query = {
      code: null, // 编码
      status: [], // 状态
      occupyStatus: [], // 渠道占用
      libraryId: [], // 库位
      colourId: [], // 成色
      typeId: [], // 设备品牌
      modelId: [], // 设备型号
      sourceList: [], // 来源
      first: null, // 首次入库时间
      machineDates: null, // 验机时间
      finished: null, // 成交入库时间
      up: null, // 上架时间
      out: null, // 出库时间
      page: 1, // 当前页
      pageSize: 20, // 分页大小
    };
    if (this.showAllDevice === 'store') {
      // @ts-ignore
      this.query.status = [0, 1];
      // @ts-ignore
      this.query.occupyStatus = [0, 2, 3];
    }
    this.queryList();
  }

  // 查询列表
  queryList(): void {
    // @ts-ignore
    const createTime = this.usedStorePService.formatTime(this.query.first ? this.query.first[0] : '', 'date');
    // @ts-ignore
    const endTime = this.usedStorePService.formatTime(this.query.first ? this.query.first[1] : '', 'date');
    // @ts-ignore
    const beginClinchTime = this.usedStorePService.formatTime(this.query.finished ? this.query.finished[0] : '', 'date');
    // @ts-ignore
    const endClinchTime = this.usedStorePService.formatTime(this.query.finished ? this.query.finished[1] : '', 'date');
    // @ts-ignore
    const beginShelvesTime = this.usedStorePService.formatTime(this.query.up ? this.query.up[0] : '', 'date');
    // @ts-ignore
    const endShelvesTime = this.usedStorePService.formatTime(this.query.up ? this.query.up[1] : '', 'date');
    // @ts-ignore
    const beginOutBoundTime = this.usedStorePService.formatTime(this.query.out ? this.query.out[0] : '', 'date');
    // @ts-ignore
    const endOutBoundTime = this.usedStorePService.formatTime(this.query.out ? this.query.out[1] : '', 'date');
    // @ts-ignore
    const beginAcceptanceTime = this.usedStorePService.formatTime(this.query.machineDates ? this.query.machineDates[0] : '', 'date');
    // @ts-ignore
    const endAcceptanceTime = this.usedStorePService.formatTime(this.query.machineDates ? this.query.machineDates[1] : '', 'date');
    this.usedStorePService.getDevices({
      ...this.query,
      colourId: this.query.colourId.join(','),
      occupyStatus: this.query.occupyStatus.join(','),
      status: this.query.status.join(','),
      libraryId: this.query.libraryId.join(','),
      typeId: this.query.typeId.join(','),
      modelId: this.query.modelId.join(','),
      createTime,
      endTime,
      beginClinchTime,
      endClinchTime,
      beginShelvesTime,
      endShelvesTime,
      beginOutBoundTime,
      endOutBoundTime,
      beginAcceptanceTime,
      endAcceptanceTime
    }).then((res: any) => {
      if (res.code === 0) {
        this.listOfData = res.data;
      }
    });
  }

  onPageIndexChange(index: number) {
    this.query.page = index;
    this.queryList();
  }

  onPageSizeChange(pageSize: number) {
    this.query.pageSize = pageSize;
    this.queryList();
  }

  // 删除
  deleteRow(id: any) {
    // this.(id).then((res: any) => {
    //   if (res.code === 0) {
    //     this.nzMessageService.success('删除成功');
    //     this.queryList();
    //   }
    // });
  }

  // 放到二手商城销售或者取回
  usedChannel(status: 0 | 2) {
    if (!this.setOfCheckedId.size) {
      this.nzMessageService.warning('请选择要操作的机器');
      return;
    }
    const message = status === 2 ? '确认将机器放到二手商城销售？' : '确认取消二手占用？';
    this.nzModalService.confirm({
      nzTitle: '<i>提示</i>',
      nzContent: `<b>${message}</b>`,
      nzOnOk: () => {
        this.usedStorePService.channelOccupy(
          this.listOfData.records.filter((i: any) => this.setOfCheckedId.has(i.id))
            .map((i: any) => i.equipmentCode).join(','), status).then((res: any) => {
          if (res.code === 0) {
            this.setOfCheckedId.clear();
            this.refreshCheckedStatus();
            this.nzMessageService.success(res.data);
            this.queryList();
          }
        });
      }
    });
  }

  view(data: any) {
    this.router.navigate(['used-store/usedDeviceDetail'], {queryParams: {deviceId: data.id}});
  }

  modifyLocation(data: any) {

  }

  // 显示修改库位模态框
  showChangeDPModal() {
    if (!this.setOfCheckedId.size) {
      this.nzMessageService.warning('请选择要修改的机器');
      return;
    }
    this.changeDLModal.visible = true;
  }

  // 修改库位提交
  hideChangeDLModalSubmit() {
    this.usedStorePService.changeDeviceLocation(this.listOfData.records.filter((i: any) => this.setOfCheckedId.has(i.id)).map((i: any) => ({
      id: i.id,
      libraryId: this.changeDLModal.libraryId,
      equipmentCode: i.equipmentCode
    }))).then(res => {
      if (res.code === 0) {
        // this.setOfCheckedId.clear();
        // this.refreshCheckedStatus();
        // this.changeDLModal.libraryId
        // this.listOfData.records.filter((i: any) => this.setOfCheckedId.has(i.id)).forEach((i: any) => {
        // })
        this.listOfData.records.forEach((i: any) => {
          if (this.setOfCheckedId.has(i.id)) {
            i.libraryName = this.locationOptions.filter((l: any) => l.id === this.changeDLModal.libraryId)[0].name;
          }
        });
        this.nzMessageService.success('操作成功');
        // this.nzMessageService.success('页面未自动刷新，请注意。');
        this.hideChangeDLModal();
        // this.queryList();
      }
    });
  }

  // 隐藏修改库位模态框
  hideChangeDLModal() {
    this.changeDLModal = {
      visible: false,
      libraryId: '',
    };
  }

  setPrint() {
    this.LODOP.SELECT_PRINTER();
  }

  print(data: any) {
    if (!this.LODOP) {
      this.nzMessageService.warning('打印插件未成功初始化，请检查是否已安装');
      return;
    }
    this.LODOP.SET_LICENSES('', 'D4E01F380814536C3C4887A0707CBBD4A4B', '', '');
    this.deviceInfo = {
      type: data.modelName,
      color: data.color,
      memory: data.memory,
      version: data.version,
      network: data.network,
      serial: data.equipmentCode,
      serialNumber: data.serialNumber,
      imei: data.imei,
      chargeCount: data.chargeCount,
      batteryHealth: data.batteryHealth,
    };
    if (this.dbclick) {
      clearTimeout(this.dbclick);
      this.dbclick = null;
      this.LODOP = getLodop(document.getElementById('LODOP_OB'), document.getElementById('LODOP_EM'));
      this.LODOP.SET_PRINT_PAGESIZE(1, 500, 250);
      this.LODOP.ADD_PRINT_HTM(0, 0, '100%', '100%', document.getElementById('printDeviceInfo')?.innerHTML);
      this.LODOP.PREVIEW();
      return;
    }
    this.dbclick = setTimeout(() => {
      this.LODOP = getLodop(document.getElementById('LODOP_OB'), document.getElementById('LODOP_EM'));
      this.LODOP.SET_PRINT_PAGESIZE(1, 500, 250);
      this.LODOP.ADD_PRINT_HTM(0, 0, '100%', '100%', document.getElementById('printDeviceInfo')?.innerHTML);
      this.LODOP.PRINT();
      this.nzMessageService.success('打印成功');
      this.dbclick = null;
    }, 500);
  }

  // 显示跟进模态框
  showTrackModal(id: string) {
    this.usedStorePService.outStoreHistory(id, 7, 2).then(res => {
      this.trackHistoryList = res.data.records;
      this.trackModal.id = id;
      this.trackModal.visible = true;
    });
  }

  // 隐藏跟进模态框
  async hideTrackModal(submit: boolean) {
    if (submit) {
      if (!this.trackModal.remark) {
        this.nzMessageService.warning('请输入跟进内容');
        return;
      }
      this.trackModal.loading = true;
      if (this.trackModal.file.length) {
        const file = new FormData();
        file.append('file', this.trackModal.file[0]);
        file.append('name', (+new Date()).toString());
        await this.usedStorePService.httpPost(this.usedStorePService.serviceUrl.fileUpload, file).then((res: any) => {
          if (res.code === 0) {
            this.trackModal.url = res.data;
          }
        });
      }
      // enclosure	附件
      // content	跟进内容
      // type	1、订单 2、售后 3、客户 4、出库 5直降  6退税 7机器
      // relationInformation	关联id
      // remarks	跟进备注
      // modelId	类型 1旧的表示二手回收 2表示二手商城 3表示二手回收
      this.usedStorePService.outStoreTrack({
        enclosure: this.trackModal.url,
        content: this.trackModal.remark,
        type: 7,
        relationInformation: this.trackModal.id,
        remarks: '',
        modelId: 2,
      }).then((result: any) => {
        if (result.code === 0) {
          this.nzMessageService.success('操作成功');
          this.trackModal = {
            visible: false,
            loading: false,
            id: '',
            url: '',
            remark: '',
            file: [],
          };
        } else {
          this.trackModal.loading = false;
          this.nzMessageService.error('操作失败');
        }
      });
    } else {
      this.trackModal = {
        visible: false,
        loading: false,
        id: '',
        url: '',
        remark: '',
        file: [],
      };
    }
  }


  showReportModal(phoneCode: any) {
    const params = {
      phoneCode
    };
    this.reportModalRef.loadData(params);
    this.reportModalRef.isVisible = true;
  }

  export() {
    this.nzModalService.confirm({
      nzTitle: '<i>提示</i>',
      nzContent: `<b>即将导出符合本页面筛选条件的订单数据，为了导出速度请尽可能控制时间范围。确定导出？</b>`,
      nzOnOk: () => {
        // @ts-ignore
        const createTime = this.usedStorePService.formatTime(this.query.first ? this.query.first[0] : '', 'date');
        // @ts-ignore
        const endTime = this.usedStorePService.formatTime(this.query.first ? this.query.first[1] : '', 'date');
        // @ts-ignore
        const beginClinchTime = this.usedStorePService.formatTime(this.query.finished ? this.query.finished[0] : '', 'date');
        // @ts-ignore
        const endClinchTime = this.usedStorePService.formatTime(this.query.finished ? this.query.finished[1] : '', 'date');
        // @ts-ignore
        const beginShelvesTime = this.usedStorePService.formatTime(this.query.up ? this.query.up[0] : '', 'date');
        // @ts-ignore
        const endShelvesTime = this.usedStorePService.formatTime(this.query.up ? this.query.up[1] : '', 'date');
        // @ts-ignore
        const beginOutBoundTime = this.usedStorePService.formatTime(this.query.out ? this.query.out[0] : '', 'date');
        // @ts-ignore
        const endOutBoundTime = this.usedStorePService.formatTime(this.query.out ? this.query.out[1] : '', 'date');
        // @ts-ignore
        const beginAcceptanceTime = this.usedStorePService.formatTime(this.query.machineDates ? this.query.machineDates[0] : '', 'date');
        // @ts-ignore
        const endAcceptanceTime = this.usedStorePService.formatTime(this.query.machineDates ? this.query.machineDates[1] : '', 'date');
        this.usedStorePService.devicesExport({
          ...this.query,
          colourId: this.query.colourId.join(','),
          occupyStatus: this.query.occupyStatus.join(','),
          status: this.query.status.join(','),
          libraryId: this.query.libraryId.join(','),
          typeId: this.query.typeId.join(','),
          modelId: this.query.modelId.join(','),
          createTime,
          endTime,
          beginClinchTime,
          endClinchTime,
          beginShelvesTime,
          endShelvesTime,
          beginOutBoundTime,
          endOutBoundTime,
          beginAcceptanceTime,
          endAcceptanceTime,
          pageSize: 999999,
        });
      }
    });
  }

  onAllChecked(checked: boolean): void {
    this.listOfData.records
      // @ts-ignore
      .filter(({disabled, status}) => !disabled && status !== 4)
      // @ts-ignore
      .forEach(({id}) => this.updateCheckedSet(id, checked));
    this.refreshCheckedStatus();
  }

  refreshCheckedStatus(): void {
    // @ts-ignore
    const listOfEnabledData = this.listOfData.records.filter(({disabled, status}) => !disabled && status !== 4);
    // @ts-ignore
    this.checked = listOfEnabledData.every(({id}) => this.setOfCheckedId.has(id));
    // @ts-ignore
    this.indeterminate = listOfEnabledData.some(({id}) => this.setOfCheckedId.has(id)) && !this.checked;
  }

  onItemChecked(id: number, checked: boolean): void {
    this.updateCheckedSet(id, checked);
    this.refreshCheckedStatus();
  }


  updateCheckedSet(id: number, checked: boolean): void {
    if (checked) {
      this.setOfCheckedId.add(id);
    } else {
      this.setOfCheckedId.delete(id);
    }
  }

  changeView() {
    this.query = {
      code: null, // 编码
      status: [], // 状态
      occupyStatus: [], // 渠道占用
      libraryId: [], // 库位
      colourId: [], // 成色
      typeId: [], // 设备品牌
      modelId: [], // 设备型号
      sourceList: [], // 来源
      first: null, // 首次入库时间
      machineDates: null, // 验机时间
      finished: null, // 成交入库时间
      up: null, // 上架时间
      out: null, // 出库时间
      page: 1, // 当前页
      pageSize: 20, // 分页大小
    };
    if (this.showAllDevice === 'store') {
      // @ts-ignore
      this.query.status = [0, 1];
      // @ts-ignore
      this.query.occupyStatus = [0, 2, 3];
    }
    this.queryList();
  }

  sourceFilter(source: number) {
    const tempObj: any = this.sourceOptions.find((item: any) => item.value === source);
    return tempObj?.label || '-';
  }

  // 重新验机入库
  againMachine(item: any) {
    this.nzModalService.confirm({
      nzTitle: '提示',
      nzContent: '确认重新验机吗？重新验机后会生成新的机器编码和信息',
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: () => {
        const routerParams: any = {
          againMachine: true, // 重新验机
          ostat: '', // 订单状态
          type: 2,
          okey: '', // 订单号
          phoneCode: item.equipmentCode // 机器编码
        };
        this.router.navigate(['/aisi-recyc/inspectedMachineEdit'], {
          queryParams: {...routerParams}
        });
      },
      nzCancelText: '取消'
    });
  }
}

